import store from '@/store'
import { i18n } from '@/lang/index'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

// 解决<input type="number" /> 在火狐浏览器下依然能输入字母的问题
export function preventNonNumericalInput(e) {
  e = e || window.event
  var charCode = typeof e.which == 'undefined' ? e.keyCode : e.which
  var charStr = String.fromCharCode(charCode)

  if (!charStr.match(/^[0-9]+$/)) e.preventDefault()
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function menuDataTranslate(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
    temp[data[i][id]]['path'] = data[i]['href']
    temp[data[i][id]]['meta'] = {
      title: data[i]['menuTitle'],
      menuId: `M_${data[i]['menuId']}`,
      icon: data[i]['icon'] ? 'menu-' + data[i]['icon'] : null
    }
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
        temp[data[k][pid]]['component'] = 'layout/Layout'
        temp[data[k][pid]]['path'] =
          '/' + data[k]['menuTitle'].replace(' ', '-').toLowerCase()
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
      const href = data[k]['href']
      if (href) {
        temp[data[k][id]]['component'] =
          href.indexOf('/') === 0 ? href : '/' + href
      }
    } else {
      if (data[k]['href']) {
        temp[data[k][id]]['component'] = 'layout/Layout'
        temp[data[k][id]]['children'] = [
          {
            path: data[k]['href'],
            component: data[k]['href'],
            meta: data[k]['meta']
          }
        ]
      }
      res.push(data[k])
    }
  }
  return res
}

export function menuDataTranslate2(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }

  for (var k = 0; k < data.length; k++) {
    // 屏蔽 openapi 权限设置，默认只有顶级运营商拥有
    if (data[k][id] === 10408090) {
      continue
    }
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['list']) {
        temp[data[k][pid]]['list'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['list'].push(data[k])
    } else {
      res.push(data[k])
    }
  }

  return res
}

export function isURL(s) {
  return /^http[s]?:\/\/.*/.test(s)
}

// 传输给服务器的版本模式
export function HTMLEncode(html) {
  var temp = document.createElement('div')
  temp.textContent != null ? (temp.textContent = html) : (temp.innerText = html)
  var output = temp.innerHTML
  temp = null
  return output
}

export const findItem = (arr, itemId) =>
  arr.reduce((a, item) => {
    if (a) return a
    if (item.id === itemId) return item
    if (item.children) return findItem(item.children, itemId)
  }, null)

// 解析出来的版本模式
export function HTMLDecode(text) {
  var temp = document.createElement('div')
  temp.innerHTML = text
  var output = temp.innerText || temp.textContent
  temp = null
  return output
}

export function menuDataTransform(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    var tempMenuData = data[i]
    if (tempMenuData.platCode === 'TOMS') {
      temp[data[i][id]] = data[i]
    }
  }
  for (var k = 0; k < data.length; k++) {
    var menuData = data[k]
    if (menuData.platCode !== 'TOMS') {
      continue
    }
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['list']) {
        temp[data[k][pid]]['list'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['list'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

export function getIcon(iconUrl, os) {
  if (iconUrl) {
    return import.meta.env.VITE_APP_BASE_API + iconUrl
  } else {
    if (!os || os.toLowerCase() == 'android') {
      iconUrl = require('@/assets/images/default-app-icon/default-android-icon.png')
    } else if (os.toLowerCase() == 'linux') {
      iconUrl = require('@/assets/images/default-app-icon/default-linux-icon.png')
    } else if (os.toLowerCase() == 'rtos') {
      iconUrl = require('@/assets/images/default-app-icon/default-rtos-icon.png')
    } else if (os.toLowerCase() == 'ota') {
      iconUrl = require('@/assets/images/default-app-icon/default-OTA-icon.png')
    } else if (os.toLowerCase() == 'win') {
      iconUrl = require('@/assets/images/default-app-icon/default-win-icon.png')
    }
    return iconUrl
  }
}

export function verifyBtnPermission(val) {
  const btnPermissions = store.getters.btnPermissions
  let hasPermission = false
  if (val) {
    if (val instanceof Array) {
      hasPermission = val.some((value) => {
        return btnPermissions.includes(value)
      })
    } else {
      hasPermission = btnPermissions.includes(val)
    }
  }
  console.log('val', val, 'hasPermission', hasPermission)
  return hasPermission
}
export function getDiskSize(num) {
  if (num == 0) return '0 Byte'
  var k = 1024 // 设定基础容量大小
  var sizeStr = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] // 容量单位
  var i = 0 // 单位下标和次幂
  for (var l = 0; l < 8; l++) {
    // 因为只有8个单位所以循环八次
    if (num / Math.pow(k, l) < 1) {
      // 判断传入数值 除以 基础大小的次幂 是否小于1，这里小于1 就代表已经当前下标的单位已经不合适了所以跳出循环
      break // 小于1跳出循环
    }
    i = l // 不小于1的话这个单位就合适或者还要大于这个单位 接着循环
  }
  return (num / Math.pow(k, i)).toFixed(3) + ' ' + sizeStr[i] // 循环结束 或 条件成立 返回字符
}

/**
 * 根据指令错误信息返回国际化处理后的内容
 * @param msg
 * @returns {string|*}
 */
export function getErrMsgInfo(msg) {
  if (msg && msg.length > 7) {
    const reg = new RegExp(/^[0-9a-fA-F]{6}\|$/)
    if (msg.indexOf('&') != -1) {
      const msgArr = msg.split('&')
      let msgInfo = ''
      msgArr.forEach((item) => {
        const prefixCode = item.substr(0, 7)
        if (reg.test(prefixCode)) {
          if (msgInfo) {
            msgInfo = msgInfo + ','
          }
          msgInfo =
            msgInfo +
            i18n.$t('modules.tms.terminal.cmd_error.' + prefixCode.substr(0, 6))
        }
      })
      return msgInfo
    } else {
      const prefixCode = msg.substr(0, 7)
      if (reg.test(prefixCode)) {
        return i18n.$t(
          'modules.tms.terminal.cmd_error.' + prefixCode.substr(0, 6)
        )
      } else {
        return msg
      }
    }
  }
  return msg
}

export function findIndex(l, o) {
  var objStr = JSON.stringify(o)
  return l.reduce((index, ele, i) => {
    if (JSON.stringify(ele) === objStr) {
      return i
    } else {
      return index
    }
  }, -1)
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  const permissions = store.getters.btnPermissions
  return permissions.includes(key)
}

export function getMapList() {
  const mapList = [
    // this.$t('cmp.page_updateFields_option')
    {
      label: 'Mapbox',
      mapType: 'MAP_BOX',
      mapKey:
        'pk.eyJ1IjoieGlhb2hhaXFpYW5nIiwiYSI6ImNsMXlmYWxyMTBjNTEza281aDY2OHc3eTMifQ.DixPNKsuzsEV740Mh-9NHA'
    },
    {
      label: 'GOOGLE MAP',
      mapType: 'GOOGLE',
      mapKey: 'AIzaSyB2tuwOcaf7U5dL7SdiqxL_x3Hx-FOq04g'
    },
    {
      label: 'BaiDu MAP',
      mapType: 'BAIDU',
      mapKey: 'K3ECtidEuUtIIKO7dYn5fLSFtt78MGQF'
    }
  ]
  return mapList
}


function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

// 将10位时间戳转为年-月-日 时:分:秒
export function toTime(time) {
  const date = new Date(time * 1000)
  const Y = date.getFullYear() + '-'
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-'
  const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '

  const h =
    (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  const m =
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  const strDate = Y + M + D + h + m + s
  return strDate
}

// 将13位时间戳转为年-月-日
export function toYMD(time) {
  const date = new Date(time)
  const Y = date.getFullYear() + '-'
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-'
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const strDate = Y + M + D
  return strDate
}

// 将10位时间戳转为年-月-日
export function toTenYMD(time) {
  const date = new Date(time * 1000)
  const Y = date.getFullYear() + '-'
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-'
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const strDate = Y + M + D
  return strDate
}

// 将13位时间戳转为年月日
export function toStandardYMD(time) {
  const date = new Date(time)
  const Y = date.getFullYear() + ''
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + ''
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const strDate = Y + M + D
  return strDate
}

// 将10位时间戳转为年月日
export function toTenStandardYMD(time) {
  const date = new Date(time * 1000)
  const Y = date.getFullYear() + ''
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + ''
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const strDate = Y + M + D
  return strDate
}

// 给金额加千分号
export function toThousands(val) {
  // 金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
  const str = val.toFixed(2) + ''
  const intSum = str
    .substring(0, str.indexOf('.'))
    .replace(/\B(?=(?:\d{3})+$)/g, ',') // 取到整数部分
  const dot = str.substring(str.length, str.indexOf('.')) // 取到小数部分搜索
  const ret = intSum + dot
  return ret
}

// 日期中间加-
export function addDiver(str) {
  const temp = str.split('')
  temp.splice(4, 0, '-')
  temp.splice(7, 0, '-')
  temp.join('')
  return temp
}

// 获取两个日期之间相差天数,传入日期格式为年月日，例如20221206
export function getDifferDays(front, after) {
  after = parseInt(after)
  let after_year = after.toString().slice(0, 4) * 365 * 24 * 60 * 60 * 1000
  let after_month = after.toString().slice(4, 6) * 30 * 24 * 60 * 60 * 1000
  let after_day = after.toString().slice(6, 8) * 24 * 60 * 60 * 1000
  after = after_year + after_month + after_day

  front = parseInt(front)
  let front_year = front.toString().slice(0, 4) * 365 * 24 * 60 * 60 * 1000
  let front_month = front.toString().slice(4, 6) * 30 * 24 * 60 * 60 * 1000
  let front_day = front.toString().slice(6, 8) * 24 * 60 * 60 * 1000
  front = front_year + front_month + front_day
  return Number(after - front) / (1000 * 60 * 60 * 24)
}

/**
 * @desc 去除标签里的style属性
 * @param {string} html html文本
 */

export function removeHtmlStyle(html) {
  var rel = /style\s*?=\s*?([‘"])[\s\S]*?\1/
  var newHtml = ''
  if (html) {
    newHtml = html.replace(rel, '')
  }
  return newHtml
}

export function uuidv4() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  )
}

// 深拷贝对象
export function deepClone(obj) {
  const _toString = Object.prototype.toString

  // null, undefined, non-object, function
  if (!obj || typeof obj !== 'object') {
    return obj
  }

  // DOM Node
  if (obj.nodeType && 'cloneNode' in obj) {
    return obj.cloneNode(true)
  }

  // Date
  if (_toString.call(obj) === '[object Date]') {
    return new Date(obj.getTime())
  }

  // RegExp
  if (_toString.call(obj) === '[object RegExp]') {
    const flags = []
    if (obj.global) {
      flags.push('g')
    }
    if (obj.multiline) {
      flags.push('m')
    }
    if (obj.ignoreCase) {
      flags.push('i')
    }

    return new RegExp(obj.source, flags.join(''))
  }

  const result = Array.isArray(obj)
    ? []
    : obj.constructor
    ? new obj.constructor()
    : {}

  for (const key in obj) {
    result[key] = deepClone(obj[key])
  }

  return result
}

const toStr = Function.prototype.call.bind(Object.prototype.toString)
export function isObjectObject(t) {
  return toStr(t) === '[object Object]'
}
export function isObjectArray(t) {
  return toStr(t) === '[object Array]'
}
export function isObjectNull(t) {
  return toStr(t) === '[object Null]'
}
export function isObjectUnde(t) {
  return toStr(t) === '[object Undefined]'
}

export function isObjectBoolean(t) {
  return toStr(t) === '[object Boolean]'
}
